package com.chan.net;

import android.net.ParseException;

import org.json.JSONException;

import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

public class DefaultRxObserver implements Observer<Result> {

    private HttpCallback httpCallback;
    private String requestCommand;

    public DefaultRxObserver(String requestCommand, HttpCallback httpCallback) {
        this.httpCallback = httpCallback;
        this.requestCommand = requestCommand;
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {

    }

    @Override
    public void onNext(@NonNull Result t) {
        dismissProgress();
        if (t.code == 0) {
            if (httpCallback != null) {
                if (t.data != null) {
                    httpCallback.onSuccess(requestCommand, t);
                } else {
                    httpCallback.onFail(requestCommand, Result.FAILCODE.CODE_DATA_EMPTY, "数据为null");
                }
            }
        }
        if (httpCallback != null) {
            httpCallback.onFail(requestCommand, t.code, t.message);
        }
    }

    private void dismissProgress() {

    }


    @Override
    public void onError(@NonNull Throwable e) {
        int code;
        String msg;
        if (e instanceof HttpException) {     //   HTTP错误
            code = Result.FAILCODE.CODE_BAD_NETWORK;
            msg = "HTTP错误";
        } else if (e instanceof ConnectException
                || e instanceof UnknownHostException) {   //   连接错误
            code = Result.FAILCODE.CODE_CONNECT_ERROR;
            msg = "连接错误";
        } else if (e instanceof InterruptedIOException) {   //  连接超时
            code = Result.FAILCODE.CODE_CONNECT_TIMEOUT;
            msg = "连接超时";
        } else if (e instanceof JSONException
                || e instanceof ParseException) {   //  解析错误
            code = Result.FAILCODE.CODE_PARSE_ERROR;
            msg = "解析错误";
        } else {
            code = Result.FAILCODE.CODE_UNKNOWN_ERROR;
            msg = "未知错误";
        }
        if (httpCallback != null) {
            httpCallback.onFail(requestCommand, code, msg);
        }
    }

    @Override
    public void onComplete() {

    }
}
